import 'dart:convert';

import 'package:byw_blog/network/NetworkInterface.dart';
import 'package:byw_blog/pages/ViewRssPage.dart';
import 'package:byw_blog/utils/ConfigUtil.dart';
import 'package:byw_blog/widget/ArticleListWidget.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webfeed/domain/rss_feed.dart';
import 'package:webfeed/domain/rss_item.dart';

import 'SearchPage.dart';

class HomePage extends StatefulWidget {
  static List<RssItem>? rss = [];

  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> categories = [];
  List<dynamic> allArticles = [];

  @override
  void initState() {
    super.initState();
    // getMicrophonePermission().then((value) {
    //   if (value) {
    //   } else {
    //     //没有权限，打开app系统设置
    //     openAppSettings();
    //   }
    // });
    // getCategories();
    NetworkInterface.getCategory().then((value) {
      List<String> type = [];
      List<dynamic> typeArticles = [];
      value.forEach((key, value) {
        type.add(key);
        typeArticles.add(value);
      });
      setState(() {
        categories.addAll(type);
        allArticles.addAll(typeArticles);
      });
    });
    getRssContent();
  }

  @override
  Widget build(BuildContext context) {
    /// 网络请求不要放在build里执行，尽量放在点击事件或生命周期执行
    /// 使用setState更新数据时，要使用DefaultTabController做局部更新，否则会重新刷新整个界面
    return DefaultTabController(
      length: categories.length,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            isScrollable: true,
            labelColor: Colors.white,
            unselectedLabelColor: Colors.white,
            indicatorSize: TabBarIndicatorSize.label,
            tabs: List.generate(categories.length, (index) {
              return Tab(
                text: categories[index].toString(),
              );
            }),
          ),
          title: const Text(
            "首页",
            style: TextStyle(color: Colors.white),
          ),
          iconTheme: const IconThemeData(color: Colors.white),
          actions: [
            IconButton(
                onPressed: () {
                  showSearch(
                      context: context,
                      delegate: SearchPage(),
                      useRootNavigator: true);
                  // Navigator.pushNamed(context, '/search');
                },
                icon: const Icon(Icons.search))
          ],
        ),
        body: TabBarView(
          children: List.generate(allArticles.length, (index1) {
            return ListView.builder(
                itemCount: allArticles[index1].length,
                itemBuilder: (context, index2) {
                  return InkWell(
                      onTap: () =>
                          clickArticle(allArticles[index1][index2]['title']),
                      child: ArticleListWidget(
                          allArticles[index1][index2]['title'],
                          allArticles[index1][index2]['author'] ?? "",
                          allArticles[index1][index2]['category']));
                });
          }),
        ),
      ),
    );
  }

  void getCategories() {
    NetworkInterface.getCategories().then((value) {
      if (value.isNotEmpty) {
        setState(() {
          categories.clear();
          categories.addAll(value);
        });
      }
    });
  }

  Future<void> getRssContent() async {
    var address = await ConfigUtil.getXmlAddress();
    final response = await get(Uri.parse(address));
    var channel = RssFeed.parse(Utf8Codec().decode(response.bodyBytes));
    setState(() {
      HomePage.rss = channel.items;
    });
  }

  clickArticle(String title) {
    HomePage.rss?.forEach((element) {
      if (element.title == title) {
        int start = element.author!.lastIndexOf('(') + 1;
        int end = element.author!.lastIndexOf(')');
        var author = element.author?.substring(start, end);
        final feedItems = {
          'title': element.title,
          // 'content':item.content!.value,
          'creator': element.dc!.creator,
          // 'image':item.media!.contents![0].url,
          'link': element.link,
          'pubDate': element.pubDate,
          'author': author,
          'content': element.content!.value
        };
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ViewRssPage(RssFeed: feedItems)));

        return;
      }
    });
  }

  ///请求权限
  Future<bool> getMicrophonePermission() async {
    // You can request multiple permissions at once.
    Map<Permission, PermissionStatus> statuses =
        await [Permission.storage].request();

    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    if (statuses[Permission.storage]!.isGranted) {
      return true;
    }
    return false;
  }
}
